<template>
  <el-card>
    <el-row>
      <el-col style="text-align: right">
        <el-button type="primary" @click="onleave">申请请假</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table
        :data="leaveList"
        style="width: 100%; overflow: auto; height: 60vh"
      >
        <el-table-column label="id" prop="id"></el-table-column>
        <el-table-column label="姓名" prop="student"></el-table-column>
        <el-table-column label="总天数" prop="leaveDay"></el-table-column>
        <el-table-column
          label="事由"
          prop="leaveReason"
          width="100"
        ></el-table-column>
        <el-table-column label="开始时间" prop="createTime"></el-table-column>
        <el-table-column label="结束时间" prop="endTime"></el-table-column>
        <el-table-column label="当前状态">
          <template #default="{ row }">
            <el-tag :type="statusTag(row.state)">{{
              stateText(row.state)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否续假" prop="renewal">
          <template #default="{ row }">
            <el-tag :type="row.renewal === 1 ? 'success' : 'primary'">{{
              row.renewal === 1 ? "是" : "否"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否销假" prop="renewalState">
          <template #default="{ row }">
            <el-tag :type="row.renewalState === 1 ? 'success' : 'primary'">{{
              row.renewalState === 1 ? "是" : "否"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              :disabled="scope.row.renewalState === 1"
              @click="renewal(scope.row)"
              >续假</el-button
            >
            <el-button
              size="small"
              type="danger"
              :disabled="scope.row.renewalState === 1"
              @click="clearance(scope.row)"
              >销假</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-pagination
          style="margin-top: 15px"
          :current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
          :page-sizes="[5, 10, 20]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </el-col>
    </el-row>
  </el-card>

  <!-- 请假对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500">
    <el-form :model="leaveListform" ref="leaveListformRef" :rules="rules">
      <el-form-item label="开始时间" label-width="100" prop="createTime">
        <el-date-picker
          v-model="leaveListform.createTime"
          type="datetime"
          placeholder="请选择开始时间"
          style="width: 240px"
          clearable
        />
      </el-form-item>

      <el-form-item label="结束时间" label-width="100" prop="endTime">
        <el-date-picker
          v-model="leaveListform.endTime"
          type="datetime"
          placeholder="请选择结束时间"
          style="width: 240px"
          clearable
        />
      </el-form-item>

      <el-form-item label="总天数" label-width="100" prop="leaveDay">
        <el-input
          v-model="leaveListform.leaveDay"
          style="width: 240px"
          disabled
          placeholder="总天数"
        ></el-input>
      </el-form-item>
      <el-form-item label="事由" label-width="100" prop="leaveReason">
        <el-input
          v-model="leaveListform.leaveReason"
          style="width: 240px"
          placeholder="事由"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { getleave, setleave, updataleave, putcancel } from "@/api/leave";
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

const leaveListformRef = ref(null);
const leaveList = ref([]);
const total = ref(0);
const searchParams = reactive({
  pageNum: 1,
  pageSize: 5,
});
const leaveListform = ref({
  leaveDay: "",
  endTime: "",
  leaveReason: "",
  createTime: "",
  id: null,
});
const dialogVisible = ref(false);
const dialogTitle = ref("申请请假");
const action = ref("add");

const handleSizeChange = (newSize) => {
  searchParams.pageSize = newSize;
  searchParams.pageNum = 1;
  getleaveList();
};

const handleCurrentChange = (newPage) => {
  searchParams.pageNum = newPage;
  getleaveList();
};

const getleaveList = async () => {
  const res = await getleave(searchParams.pageNum, searchParams.pageSize);
  leaveList.value = res.data.rows;
  total.value = res.data.total;
};

const calculateDays = (createDate, endDate) => {
  const create = new Date(createDate);
  const end = new Date(endDate);
  const diffTime = Math.abs(end - create);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays;
};

watch(
  () => [leaveListform.value.createTime, leaveListform.value.endTime],
  ([newStart, newEnd]) => {
    if (newStart && newEnd) {
      const leaveDay = calculateDays(newStart, newEnd);
      leaveListform.value.leaveDay = leaveDay;
    }
  },
  { immediate: false }
);

const onleave = () => {
  dialogVisible.value = true;
  dialogTitle.value = "申请请假";
  action.value = "add";
};

const renewal = (row) => {
  if (row.renewalState === 1) {
    ElMessage({
      message: "销假后，不允许续假",
      type: "warning",
    });
    return;
  }
  dialogVisible.value = true;
  dialogTitle.value = "申请续假";
  leaveListform.value = { ...row };
  action.value = "edit";
};

const clearance = (row) => {
  if (row.renewalState === 1) {
    ElMessage({
      message: "已经销假了哦",
      type: "warning",
    });
    return;
  }
  ElMessageBox.confirm("确认要销假吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      performClearance(row);
      ElMessage.success("销假成功");
    })
    .catch(() => {
      ElMessage.warning("销假操作已取消");
    });
};

const performClearance = async (row) => {
  try {
    const data = {
      id: row.id,
      studentName: row.studentName,
      days: row.days,
      reason: row.reason,
      createTime: row.createTime,
      endTime: row.endTime,
      state: row.state,
      renewalState: 1,
    };
    const res = await putcancel(data);
    if (res.data.code === 200) {
      ElMessage({
        message: "销假成功",
        type: "success",
      });
      getleaveList();
    } else {
      ElMessage({
        message: "销假失败",
        type: "error",
      });
    }
  } catch (error) {
    console.error("销假请求失败", error);
    ElMessage({
      message: "销假请求失败",
      type: "error",
    });
  }
};

const rules = ref({
  createTime: [
    { required: true, message: "请选择开始时间", trigger: "change" },
  ],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
  leaveReason: [{ required: true, message: "请输入事由", trigger: "blur" }],
});

// 提交表单
const submitForm = async () => {
  if (leaveListformRef.value) {
    await leaveListformRef.value.validate(async (valid) => {
      if (valid) {
        console.log("表单验证通过");
        console.log(leaveListform.value); // 打印表单数据以确保正确性    // 格式化日期时间为 "yyyy-MM-dd'T'HH:mm:ss'Z'"
        const startDatePicker = leaveListform.value.createTime;
        const endDatePicker = leaveListform.value.endTime;
        const newStartDate = new Date(startDatePicker);
        const newEndDate = new Date(endDatePicker);

        newStartDate.toISOString = function () {
          return (
            this.getFullYear() +
            "-" +
            ("0" + (this.getMonth() + 1)).slice(-2) +
            "-" +
            ("0" + this.getDate()).slice(-2) +
            "T" +
            ("0" + this.getHours()).slice(-2) +
            ":" +
            ("0" + this.getMinutes()).slice(-2) +
            ":" +
            ("0" + this.getSeconds()).slice(-2) +
            "Z"
          );
        };
        const formattedStartDate = newStartDate.toISOString();

        newEndDate.toISOString = function () {
          return (
            this.getFullYear() +
            "-" +
            ("0" + (this.getMonth() + 1)).slice(-2) +
            "-" +
            ("0" + this.getDate()).slice(-2) +
            "T" +
            ("0" + this.getHours()).slice(-2) +
            ":" +
            ("0" + this.getMinutes()).slice(-2) +
            ":" +
            ("0" + this.getSeconds()).slice(-2) +
            "Z"
          );
        };
        const formattedEndDate = newEndDate.toISOString();

        // 更新表单数据
        leaveListform.value.createTime = formattedStartDate;
        leaveListform.value.endTime = formattedEndDate;

        if (action.value === "add") {
          try {
            console.log(leaveListform.value);
            const res = await setleave(leaveListform.value);

            ElMessage({
              message: "申请请假成功",
              type: "success",
            });
          } catch (error) {
            ElMessage({
              message: "申请请假失败",
              type: "error",
            });
          }
        } else {
          try {
            const res = await updataleave(leaveListform.value);
            console.log(res);

            if (res.data.code === 200) {
              ElMessage({
                message: "申请续假成功",
                type: "success",
              });
            } else {
              ElMessage({
                message: "续假失败",
                type: "error",
              });
            }
          } catch (error) {
            ElMessage({
              message: "续假请求失败",
              type: "error",
            });
          }
        }

        // 完成后关闭对话框
        dialogVisible.value = false;
        // 重新获取请假列表
        getleaveList();
      } else {
        console.log("表单验证失败");
        return false;
      }
    });
  }
};

// 状态标签类型
const statusTag = (state) => {
  switch (state) {
    case 0:
      return "info";
    case 1:
      return "warning";
    case 2:
      return "success";
    default:
      return "info";
  }
};

// 监听对话框的可见性变化
watch(dialogVisible, (newValue) => {
  if (!newValue) {
    // 当对话框关闭时，清空表单数据
    leaveListform.value = {
      days: "",
      endTime: "",
      leaveReason: "",
      createTime: "",
    };
  }
});

// 状态文本
const stateText = (state) => {
  switch (state) {
    case 0:
      return "正常";
    case 1:
      return "请假审核中";
    case 2:
      return "休假中";
    default:
      return "未知状态";
  }
};

// 钩子函数
onMounted(() => {
  getleaveList();
});
</script>

<style scoped></style>
